package com.sss.ordermodel.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.sss.common.entities.Product;
import com.sss.common.responseutil.Result;
import com.sss.ordermodel.dao.IOrdersDetailDao;
import com.sss.ordermodel.entities.OrderSss;
import com.sss.ordermodel.dao.IOrderSssDao;
import com.sss.ordermodel.entities.OrdersDetail;
import com.sss.ordermodel.feignservice.ProductService;
import com.sss.ordermodel.service.IOrderSssService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sss.ordermodel.vo.OrderVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sss
 * @since 2020-04-06
 */
@Service
public class OrderSssServiceImpl extends ServiceImpl<IOrderSssDao, OrderSss> implements IOrderSssService {

    @Resource
    private IOrderSssDao orderSssDao;
    @Resource
    private IOrdersDetailDao ordersDetailDao;
    @Autowired
    private ProductService productService;


    @GlobalTransactional(name = "order-sss",rollbackFor = Exception.class)
    @Transactional
    public Integer saveOrder(OrderVO orderVO) {
        /** 下订单**/
        //随机生成用户ID
        int userId= RandomUtil.randomInt(1, 1000000);
        //支付总金额
        BigDecimal payAmount = orderVO.getProductPrice().multiply(new BigDecimal(orderVO.getProductQuantity()));
        orderVO.setOrderType(1);
        orderVO.setUserId(userId);
        orderVO.setReceiverName("张三");
        orderVO.setReceiverPhone("147895666");
        orderVO.setReceiverAddress("广东省广州市");
        orderVO.setPayAmount(payAmount);
        orderSssDao.saveOrder(orderVO);
        /**商品库存扣减**/
        Integer productId1 = Integer.valueOf(orderVO.getProductId());
        Result<Product> product1 = productService.getProductById(productId1);
        //旧的商品库存
        Integer oldStockNumber = product1.getData().getStockNumber();
        Product product = new Product();
        product.setStockNumber(oldStockNumber - orderVO.getProductQuantity());
        productService.productUpdate(productId1,product);
        /** 订单详情 **/
        Integer orderId = orderVO.getId();
        OrdersDetail ordersDetail = new OrdersDetail();
        ordersDetail.setOrderId(orderId);
        ordersDetail.setProductId(orderVO.getProductId());
        ordersDetail.setProductName(orderVO.getProductName());
        ordersDetail.setProductPrice(orderVO.getProductPrice());
        ordersDetail.setProductQuantity(orderVO.getProductQuantity());
        ordersDetailDao.insert(ordersDetail);
        return orderVO.getId();
    }

    @Override
    public List<OrderSss> getOrderById(Integer orderId) {
        return orderSssDao.getOrderById(orderId);
    }
}
